# dictionary with loading/saving capabilities

import pickle
import errno
import logging
from UserDict import UserDict

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s.%(msecs)03d %(lineno)d %(levelname)s %(message)s',
                    datefmt='%H:%M:%S')
log = logging.getLogger('db')

FILENAME = 'avdb.txt'

class PersistentDict(UserDict):
    'Simple database class, really a wrapper for a dict'
    def __init__(self, filename=FILENAME):
        UserDict.__init__(self)
        self.filename = filename
        try:
            with open(filename, 'r') as self.dbfile:
                log.debug("loading database from %s", filename)
                self.data = pickle.load(self.dbfile)
        except IOError as e:
            if e.errno == errno.ENOENT:
                log.debug("%s doesn't exist... creating new database", filename)
            else:
                raise

    def save(self):
        with open(self.filename, 'w') as self.dbfile:
            log.debug("saving database to %s", self.filename)
            pickle.dump(self.data, self.dbfile)   

if '__name__' == '__main__':
    d = PersistentDict('hello.txt')
    print 'd =', d
    d['something else'] = 'there'
    d[45] = '99'
    print 'd =', d
    d.save()
